var gulp = require('gulp');
var del = require('del');
var chalk = require('chalk')
var imagemin = require('gulp-imagemin');
var babel = require('gulp-babel');
var base64 = require('gulp-base64');
var htmlminify = require('gulp-html-minify');
var useref = require('gulp-useref');
var uglify = require("gulp-uglify")
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var ejs = require("gulp-ejs")
var postcss = require('gulp-postcss');
var rev = require('gulp-rev');
var rename = require("gulp-rename");
var autoprefixer = require('autoprefixer');
var cssnano = require('cssnano');
var precss = require('precss');
var plumber = require('gulp-plumber');
var watch = require('gulp-watch');
var gulpIf = require('gulp-if');
var path = require("path")

var config
try {
    config = require(path.resolve(process.cwd() + "/stagu.config"))
} catch (e) {
    config = {}
}

var vaUtil = {
    isMinify: function (config, tag) {
        var tagObj = config[tag] || {}
        var minify = tagObj.minify === undefined ? true : tagObj.minify
        return minify
    }
};


var devServeDir = ".stagu"; //开发serve目录
var devDir = "./" + devServeDir //开发目录
var buildDir = "./dist"
var srcDir = path.resolve(process.cwd(),"./src") //源代码目录

function isDev() {
    var NODE_ENV = process.env.NODE_ENV || "development";
    return NODE_ENV === "development"
}

var destDir = isDev() ? devDir : buildDir;


/**
 * build
 */
gulp.task('clean', function (cb) {
    del(destDir + '/*', cb).then(path => {
        console.log(chalk.red("delete " + path));
        cb()
    })
});

gulp.task('js', ['clean'], function (cb) {
    gulp.src(srcDir + '/**/*.js')
        .pipe(plumber())
        .pipe(babel({
            presets: ['env']
        }))
        .pipe(gulpIf(!isDev() && vaUtil.isMinify(config, "js"), uglify()))
        .pipe(gulp.dest(destDir));
    cb();
});


gulp.task('html', ["clean", "image", "css"], function (cb) {
    gulp.src(srcDir + '/**/*.html',)
        .pipe(plumber())
        .pipe(gulpIf(!isDev(), useref()))
        .pipe(gulpIf(!isDev() && vaUtil.isMinify(config, "html"), htmlminify()))
        .pipe(gulp.dest(destDir))
        .pipe(gulpIf(isDev(), reload({
            stream: true
        })));
    cb()
});


gulp.task('ejs', ['clean', 'image', "css"], function (cb) {
    gulp.src([srcDir + '/**/*.ejs', '!' + srcDir + '/template/*.ejs'],)
        .pipe(plumber())
        .pipe(ejs(config.template || {}, {}, {
            ext: '.html'
        }))
        .pipe(gulpIf(!isDev(), useref()))
        .pipe(gulpIf(!isDev() && vaUtil.isMinify(config, "html"), htmlminify()))
        .pipe(gulp.dest(destDir))
        .pipe(gulpIf(isDev(), reload({
            stream: true
        })));
    cb();
});


gulp.task('css', ['clean'], function (cb) {
    var plugins = [
        autoprefixer({
            browsers: ['last 1 version']
        }),
    ];
    if (!isDev()) {
        plugins.push(precss);
    }
    if (!isDev() && vaUtil.isMinify(config, "css")) {
        plugins.push(cssnano());
    }

    gulp.src(srcDir + '/**/*.css')
        .pipe(plumber())
        .pipe(gulpIf(!isDev(), base64({
            maxImageSize: 8 * 1024,
        })))
        .pipe(postcss(plugins))
        .pipe(gulp.dest(destDir));
    cb()
});

gulp.task('image', ['clean'], function (cb) {
    gulp.src(srcDir + '/**/*.{jpg,png,gif,ico}')
        .pipe(plumber())
        .pipe(gulpIf(!isDev(), imagemin()))
        .pipe(gulp.dest(destDir));
    cb()
});

var tasks;
if (isDev()) {
    tasks = function () {
        browserSync({
            server: {
                baseDir: devServeDir
            }
        });
        var watcher = watch(srcDir + '/**/*.{ejs,html,css,js}', function () {
            gulp.start(["html", "ejs", "js"])
        });
        watcher.on('change', function (event) {
            console.log('File ' + event + ' was change, running tasks...');
        });
        watcher.on('error', function (error) {
            console.log(error);
        });
    }
}
gulp.task('default', ["html", "ejs", "js"], tasks);
module.exports = gulp
